package com.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.xutils.DbManager;
import org.xutils.x;
import org.xutils.DbManager.DaoConfig;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.MeasureSpec;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class TTUtils {

	
	public static SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**
	 * toast信息
	 * @param context
	 * @param message
	 */
	public static void toast(Context context,String message){
		Toast.makeText(context, message, Toast.LENGTH_LONG).show();
	}
	/** 
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 
     */  
    public static int dip2px(Context context, float dpValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (dpValue * scale + 0.5f);  
    }  
  
    /** 
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp 
     */  
    public static int px2dip(Context context, float pxValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (pxValue / scale + 0.5f);  
    }  
  
    /**
     * 获得bitmap
     * @param path
     * @param width
     * @param height
     * @return
     */
	public static Bitmap getBitmap(String path, int width, int height){
		Bitmap bitmap = null;
		try {
			
			if(bitmap == null){
				try {	
					bitmap = getBitmapFromFile(new File(path), width, height);
					
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;
	}
	
	/**
	 * 获得图片对象
	 * @param dst
	 * @param width
	 * @param height
	 * @return
	 */
	private static Bitmap getBitmapFromFile(File dst, int width, int height) {  
	    if (null != dst && dst.exists()) {  
	        BitmapFactory.Options opts = null;  
	        if (width > 0 && height > 0) {  
	            opts = new BitmapFactory.Options();  
	            opts.inJustDecodeBounds = true;  
	            BitmapFactory.decodeFile(dst.getPath(), opts);  
	            // 计算图片缩放比例  
	            final int minSideLength = Math.min(width, height);  
	            opts.inSampleSize = computeSampleSize(opts, minSideLength,  width * height);  
	            opts.inJustDecodeBounds = false;  
	            opts.inInputShareable = true;  
	            opts.inPurgeable = true;  
	        }  
	        try {  
	            return BitmapFactory.decodeStream(new FileInputStream(dst.getPath()), null, opts);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	    }  
	    return null;  
	}  
	/**
	 * 限制缩放比例  
	 * @param options
	 * @param minSideLength
	 * @param maxNumOfPixels
	 * @return
	 */
	private static int computeSampleSize(BitmapFactory.Options options,  
	        int minSideLength, int maxNumOfPixels) {  
	    int initialSize = computeInitialSampleSize(options, minSideLength,  
	            maxNumOfPixels);  
	  
	    int roundedSize;  
	    if (initialSize <= 8) {  
	        roundedSize = 1;  
	        while (roundedSize < initialSize) {  
	            roundedSize <<= 1;  
	        }  
	    } else {  
	        roundedSize = (initialSize + 7) / 8 * 8;  
	    }  
	  
	    return roundedSize;  
	}  
	/**
	 * 获得缩放比例  
	 * @param options
	 * @param minSideLength
	 * @param maxNumOfPixels
	 * @return
	 */
	private static int computeInitialSampleSize(BitmapFactory.Options options,  
	        int minSideLength, int maxNumOfPixels) {  
	    double w = options.outWidth;  
	    double h = options.outHeight;  
	  
	    int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math  
	            .sqrt(w * h / maxNumOfPixels));  
	    int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math  
	            .floor(w / minSideLength), Math.floor(h / minSideLength));  
	  
	    if (upperBound < lowerBound) {  
	        // return the larger one when there is no overlapping zone.  
	        return lowerBound;  
	    }  
	  
	    if ((maxNumOfPixels == -1) && (minSideLength == -1)) {  
	        return 1;  
	    } else if (minSideLength == -1) {  
	        return lowerBound;  
	    } else {  
	        return upperBound;  
	    }  
	}  
	/**
	 * 获取相册图片地址
	 * @param context
	 * @param originalUri
	 * @return
	 */
	public static String getImageUrl(Context context, Uri originalUri) {
        String result = "";
        ContentResolver resolver = context.getContentResolver();
//        Bitmap bm = null;
        try {
//            bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);
            String[] proj = {MediaStore.Images.Media.DATA};
//            Cursor cursor = managedQuery(originalUri, proj, null, null, null);
            Cursor cursor = resolver.query(originalUri, proj, null, null, null);
//            Cursor cursor = new CursorLoader(this, originalUri, proj, null, null, null).loadInBackground();
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            //最后根据索引值获取图片路径
            result = cursor.getString(column_index);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
	/**
	 * 压缩保存图片
	 * @param path
	 * @param width
	 * @param height
	 * @param isDelete
	 * @return
	 */
	public static String saveImage(String path, int width, int height,boolean isDelete,String name,double lag,double log){
		FileOutputStream out = null;
		try {
			Bitmap bitmap = getBitmap(path, width, height);
			
			Canvas canvas = new Canvas(bitmap);// 初始化画布 绘制的图像到icon上

			// 设置画笔
			Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
			textPaint.setTextSize(20.0f);// 字体大小
			textPaint.setColor(Color.RED);
			
			//gps
			String gps = lag + "," + log;
			Rect rTop = new Rect();
			textPaint.getTextBounds(gps, 0, gps.length(), rTop);
			
			canvas.drawText(gps, bitmap.getWidth() - rTop.width(),bitmap.getHeight() - rTop.height(),  textPaint);
			
			
			//name
			Rect lBottom = new Rect();
			textPaint.getTextBounds(name, 0, name.length(), lBottom);
			canvas.drawText(name, 3,bitmap.getHeight() - lBottom.height(),  textPaint);
			
			String date = sf.format(new Date());
			Rect rBottom = new Rect();
			textPaint.getTextBounds(date, 0, date.length(), rBottom);
			canvas.drawText(date, 3,bitmap.getHeight() - lBottom.height(),  textPaint);
			
			
			
			File vFile = new File(Environment.getExternalStorageDirectory()
					+ "/safe/", String.valueOf(System.currentTimeMillis())
					+ ".png");
			
			if (!vFile.exists())
			{
				File vDirPath = vFile.getParentFile();
				vDirPath.mkdirs();

			}
			out = new FileOutputStream(vFile);
			bitmap.compress(CompressFormat.PNG, 100, out);
			out.close();
			
			if (isDelete) {
				File file = new File(path);
				file.delete();
			}
			
			path = vFile.getAbsolutePath();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		return path;
	}
	/**
	 * 播打电话
	 * @param context
	 * @param phone
	 */
	public static void makePhone(Context context,String phone){
		Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+phone)); 
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent); 
	}
	
	
	/**
	 * 获取版本号
	 * @return 当前应用的版本号
	 */
	public static String getVersion(Context context) {
	    try {
	        PackageManager manager = context.getPackageManager();
	        PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
	        String version = "" + info.versionCode;
	        return  version;
	    } catch (Exception e) {
	        e.printStackTrace();
	        return "";
	    }
	}
	
	  /**
     * 设置listView高度
     * @param listView
     */
    public static  void setListViewHeightBasedOnChildren(ListView listView) {
		try {
			ListAdapter listAdapter = listView.getAdapter();
			if (listAdapter == null) {
			// pre-condition
			return;
			}
			int totalHeight = 0;
			for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			// listItem.measure(0, 0);
			listItem.measure(
			MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
			MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
			totalHeight += listItem.getMeasuredHeight();
			}
			ViewGroup.LayoutParams params = listView.getLayoutParams();
			params.height = totalHeight
			+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
			listView.setLayoutParams(params);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		}
    /**
     * MD5加密
     * @param plainText
     * @return
     */
    public static String MD5(String plainText) {
		String re_md5 = new String();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();

			int i;

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}

			re_md5 = buf.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return re_md5;
	}
    
    
	
	/**
	 * 判断是否有sd卡
	 * @return
	 */
	public boolean havaSDCard(){
		boolean flag = false;
		try {
			if (Environment.getExternalStorageState().equals(  
				    android.os.Environment.MEDIA_MOUNTED)){
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	/**
	 * 判断是否可存储图片（剩余内存最少8MB）
	 * @return
	 */
	public boolean canSave(){
		boolean flag = false;
		try {		
			 File path = Environment.getExternalStorageDirectory();   
		     StatFs sf = new StatFs(path.getPath());   
		     //获取单个数据块的大小(Byte)  
		     long blockSize = sf.getBlockSize();   
		     //空闲的数据块的数量  
		     long freeBlocks = sf.getAvailableBlocks(); 
		     
		     long mb = (freeBlocks * blockSize)/1024/1024;
		     if(mb > 8){
		    	 flag = true;
		     }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
}
